<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request; 
use App\Model\{Admin,User,Config,Cat,Article}; 
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Libraries\vendor\Sms;
use GeoIp2\Database\Reader;
use App\Libraries\vendor\SphinxClient;

/**
 * @menu_cat 内容审核
 * @icon cog
 * @sort 30
 */
class ArticleController extends Controller
{	
	public $field = [
		'id',
		'admin_id',
		'g_id',
		'top',
		'set_top',
		'title',
		'pic',
		'type',
		'is_hot',
		'show_pv',
		'pv',
		'pv_max',
		'money',
		'day',
		'status',
		'downline',
		'source',
		'type_of_article',
		'length_time',
		'grab',
		'primary_url',
		'ar_source',
		'words_number',
	];
	public $vide_field = [
		'id',
		'admin_id',
		'g_id',
		'top',
		'set_top',
		'title',
		'pic',
		'type',
		'is_hot',
		'show_pv',
		'pv',
		'pv_max',
		'money',
		'day',
		'status',
		'downline',
		'source',
		'type_of_article',
		'length_time',
		'grab',
		'primary_url',
		'ar_source',
		'words_number',
		'md_title',
		'video_size',
	];

    public function __invoke(){
        return $this->index(func_get_args());
    }


    /**
     * @menu 文章待审核
     * @return [type] [description]
     */
    public function article(){
    	$list = DB::connection('db2')->table('article')->select($this->field);
        $this->_search($list, $search,[],[],'line_article',$words);
        
        if($search['refund']==1){
            $map[] = ['status','=',2];
        }else{
            $map[] = ['status','=',1];
        }
        $map[] =  ['downline','=',0];
        $map[] =  ['grab','>',0];
        $map[] = ['type','>',0];
        $map[] =  ['on_queue','=',0];
        $map[] =  ['ymd','>',date('Ymd',strtotime("-3 day"))];



        

        #$article_cats = DB::table('admindata')->where('id',$this->admin['id'])->first(['article_cats']);
        #$article_cats = json_decode($article_cats->article_cats,true);
        #$list->where($map)->whereIn('type',$article_cats)->whereIn('type_of_article',[1,2]);
        $list->where($map)->whereIn('type_of_article',[1,2]);
        $this->_order($list, ['id'=>'asc']);
        $list = Article::article_list($list,$words);
        return view('Admin.Article.index')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::article_cat(),
        ]);
    }


    /**
     * @menu 视频待审核
     * @sort 0
     * @return [type] [description]
     */
    public function video(){
        $list = DB::connection('db2')->table('video')->select($this->field);
        $this->_search($list, $search,[],[],'line_video',$words);

        if($search['refund']==1){
            $map[] = ['status','=',2];
        }else{
            $map[] = ['status','=',1];
        }
        $map[] = ['downline','=',0];
        $map[] = ['grab','>',0];
        if($search['type']!=84) {
           $map[] = ['ymd','>',date('Ymd',strtotime("-3 day"))]; 
        }
        $map[] = ['type','>',0];
        $map[] = ['on_queue','=',0];
        

    
        
        #$video_cats = DB::table('admindata')->where('id',$this->admin['id'])->first(['video_cats']);
        #$video_cats = json_decode($video_cats->video_cats,true);
        #$list->where($map)->whereIn('type',$video_cats)->whereIn('type_of_article',[3]);
        $list->where($map)->whereIn('type_of_article',[3]);
        $this->_order($list, ['id'=>'asc']);
        $list = Article::article_list($list,$words);

        return view('Admin.Video.index')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::video_cat(),
        ]);
    }


    /**
     * @name 审核查看文章
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function info($id){
        if(request()->isMethod('post')){
            $param=request()->only('cat_id','id');
            $cat_id = $param['cat_id'];
            $bool = DB::connection('db2')->table('article')->where('id',$param['id'])->update([
                'type'=>$cat_id
            ]);

            return redirect('/article/info/'.$id."#set");
        }
    	$data = Article::info(['id'=>$id]);
        $cats = Article::article_cat();
    	return view('Admin.Article.info',[
    		'data' => $data,
            'cats'=>$cats,
    	]);
    }

    /**
     * 文章通过审核
     * @return [type] [description]
     */
    public function ajax_adopt($id){
    	/*
    	$bool = DB::table('article')->where('id',$id)->update([
    		'status'=>0,
    		'downline'=>1,
    	]);
    	*/

    	$bool = DB::connection('db2')->table('article')->where('id',$id)->update([
    		'on_queue'=>1,
            'status'=>1,
    	]);
        $data = DB::connection('db2')->table('article')->where('id',$id)->first(['type_of_article','type']);
    	if($bool!=false){
    		$aa = Article::add_queue([
	    		'type'=>0,
	    		'article_id'=>$id,
                'admin_id'=>$this->admin['id'],
                'cat_id'=>$data->type,

	    	]);

    		Article::log([
    			'admin_id'=>$this->admin['id'],
    			'name'=>$this->admin['name'],
    			'article_id'=>$id,
    			'status'=>1,
    			'type'=>$data->type_of_article==3?1:0,
                
    		]);
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }

    /**
     * 审核不通过
     */
    public function ajax_refund($id){
        if( DB::table('check_article_queue')->where('exec',0)->where('type',0)->where('article_id',$id)->exists() ){
            return response()->json(['status'=>0,'info'=>"该文章已经被审核通过，不能拒绝！"]);
        }

    	$bool = DB::connection('db2')->table('article')->where('id',$id)->update([
    		'status'=>2,
    	]);
    	if($bool!=false){
    		Article::log([
    			'admin_id'=>$this->admin['id'],
    			'name'=>$this->admin['name'],
    			'article_id'=>$id,
    			'status'=>2,
    			'type'=>0,
    		]);
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }

    public function ajax_batch_refund(){
        $post = request()->only(['ids']);
        $ids = explode(',', $post['ids']);
        foreach($ids as $id){
            if( DB::table('check_article_queue')->where('exec',0)->where('type',0)->where('article_id',$id)->exists() ){
                continue;
            }
            
            $bool = DB::connection('db2')->table('article')->where('id',$id)->update([
                'status'=>2,
            ]);
            if($bool!=false){
                Article::log([
                    'admin_id'=>$this->admin['id'],
                    'name'=>$this->admin['name'],
                    'article_id'=>$id,
                    'status'=>2,
                    'type'=>0,
                ]);
            }
        }
        return response()->json([
            'status'=>1,
        ]);
    }

    public function ajax_unrefund($id){
        $bool = DB::connection('db2')->table('article')->where('id',$id)->update([
            'status'=>0,
        ]);
        if($bool){
            die(json_encode(['status'=>1,'info'=>'success']));
        }else{
            die(json_encode(['status'=>0,'info'=>'fail']));
        }
    }

    /**
     * 设置分类
     */
     public function ajax_set_cat($id){
     	$param = request()->only(['type']);
     	$bool = $param['type'] && DB::connection('db2')->table('article')->where('id',$id)->update([
    		'type'=>$param['type'],
    	]);
    	if($bool!=false){
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }

    /**
     * #@menu 视频待审核
     * @return [type] [description]
     */
    public function videobak(){
    	$list = DB::table('video')->select($this->field);
        $this->_search($list, $search);

        $list->where([
        	['status','=',1],
        	['on_queue','=',0]
        ])->whereIn('type',$this->admin['video_cats']);

        $this->_order($list, ['id'=>'desc']);
        $list = Article::video_list($list);

        return view('Admin.Article.video_index')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::video_cat(),
        ]);
    }

    /**
     * #@name 审核查看视频
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function video_info($id){
        if(request()->isMethod('post')){
            $param=request()->only('cat_id','id');
            $cat_id = $param['cat_id'];
            $bool = DB::connection('db2')->table('video')->where('id',$param['id'])->update([
                'type'=>$cat_id
            ]);
            return redirect('/article/video_info/'.$id."#set");
        }

    	$data = DB::connection('db2')->table('video')->where('id',$id)->first();
        $cats = Article::video_cat();
    	return view('Admin.Article.video_info',[
    		'data' => $data,
            'cats'=>$cats,
    	]);
    }

    public function ajax_local_video($id){
        
        $data = DB::table('article')->where('id',$id)->first();
        $cats = Article::video_cat();
        return view('Admin.Article.video_info',[
            'data' => $data,
            'cats'=>$cats,
        ]);
    }

    public function ajax_local_article($id){
         
        $data = DB::table('article')->where('id',$id)->first();
        $cats = Article::article_cat();
        return view('Admin.Article.info',[
            'data' => $data,
            'cats'=>$cats,
        ]);
    }


    /**
     * 视屏通过审核
     * @return [type] [description]
     */
    public function ajax_video_adopt($id){
    	/*
    	$bool = DB::table('video')->where('id',$id)->update([
    		'status'=>0,
    		'downline'=>1,
    	]);
    	*/
    	$bool = DB::connection('db2')->table('video')->where('id',$id)->update([
    		'on_queue'=>1,
            'status'=>1,
    	]);
        $data = DB::connection('db2')->table('video')->where('id',$id)->first(['type']);
    	if($bool!=false){
    		Article::add_queue([
	    		'type'=>1,
	    		'article_id'=>$id,
                'admin_id'=>$this->admin['id'],
                'cat_id'=>$data->type,
	    	]);

    		Article::log([
    			'admin_id'=>$this->admin['id'],
    			'name'=>$this->admin['name'],
    			'article_id'=>$id,
    			'status'=>1,
    			'type'=>1,
    		]);
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }

    /**
     * 视屏审核不通过
     */
    public function ajax_video_refund($id){
        if( DB::table('check_article_queue')->where('exec',0)->where('type',1)->where('article_id',$id)->exists() ){
            return response()->json(['status'=>0,'info'=>"该视频已经被审核通过，不能拒绝！"]);
        }
    	$bool = DB::connection('db2')->table('video')->where('id',$id)->update([
    		'status'=>2,
    	]);
    	if($bool!=false){
    		Article::log([
    			'admin_id'=>$this->admin['id'],
    			'name'=>$this->admin['name'],
    			'article_id'=>$id,
    			'status'=>2,
    			'type'=>1,
    		]);
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }
    public function ajax_video_batch_refund(){
        $post = request()->only(['ids']);
        $ids = explode(',', $post['ids']);
        foreach($ids as $id){
            if( DB::table('check_article_queue')->where('exec',0)->where('type',1)->where('article_id',$id)->exists() ){
                continue;
            }
            
            $bool = DB::connection('db2')->table('video')->where('id',$id)->update([
                'status'=>2,
            ]);
            if($bool!=false){
                Article::log([
                    'admin_id'=>$this->admin['id'],
                    'name'=>$this->admin['name'],
                    'article_id'=>$id,
                    'status'=>2,
                    'type'=>1,
                ]);
            }
        }
        return response()->json([
            'status'=>1
        ]);
    }
    /**
     * 设置分类
     */
     public function ajax_video_set_cat($id){
     	$param = request()->only(['type']);
     	$bool = $param['type'] && DB::connection('db2')->table('video')->where('id',$id)->update([
    		'type'=>$param['type'],
    	]);
    	if($bool!=false){
    		die(json_encode(['status'=>1,'info'=>'success']));
    	}else{
    		die(json_encode(['status'=>0,'info'=>'fail']));
    	}
    }

    /**
     * #@menu 文章抓取统计
     * @return [type] [description]
     */
    public function article_tongji(){
    	$day = 10;
    	$days = [];
    	while($day>0){
    		$days[] = date('Ymd',strtotime("-$day day",time()));
    		$day--;
    	}

    	$data = [];
    	$cats = Article::article_cat();
    	foreach($cats as $cat_id=>$cat){
    		$source = DB::table('check_tongji')->where('type',0)->where('cat_id',$cat_id)->whereIn('ymd',$days)->get()->toArray();
    		$source = arrays_set_key($source,'ymd');
    		$x = [];
    		foreach($days as $d){
    			$x['collection'][] = isset($source[$d])?$source[$d]->collection_number:0;
    			$x['insert'][] = isset($source[$d])?$source[$d]->insert_number:0;
    		}
    		$data[] = [
    			'cat_id'=>$cat_id,
    			'name'=>$cat->name,
    			'data'=>$x,
    		];
    	}
    	#dd($data);
    	return view('Admin.Article.article_tongji',[
    		'data'=>$data,
    		'days'=>$days,
    	]);
    }

    /**
     * @menu 抓取统计
     */
    public function spider(){
    	$list = DB::table('check_tongji');
        $this->_search($list, $search);
        $this->_order($list, ['id'=>'desc']);

        if(!isset($search['ymd'])){
            $list->where('ymd',date('Ymd'));
            $search['ymd'] = date('Ymd');
        }

        $list = $list->paginate(20);
        return view('Admin.Article.spider')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::article_cat(),
            'video_cats'=>Article::video_cat(),
        ]);
    }
    

    /**
     * @menu 已审统计(每3分钟更新)
     * @return [type] [description]
     */
    public function check_log_tongji(){
    	$list = DB::table('check_log_tongji');
        $this->_search($list, $search);
        $this->_order($list, ['id'=>'desc']);
        $admin = DB::table('admindata')->where('id',$this->admin['id'])->first(['group_id']);
        if(!isset($search['ymd'])){
            $list->where('ymd',date('Ymd'));
            $search['ymd'] = date('Ymd');
        }
        if($admin->group_id==2){
            $list->where('admin_id',$this->admin['id']);
        }

        $sum = $list->sum('total');
        $list = $list->paginate(20);
       
        return view('Admin.Article.check_log_tongji')->with([
            'list' => $list,
            '_search'=>$search,
            'users'=>Admin::all_list(),
            'cats'=>Article::article_cat(),
            'video_cats'=>Article::video_cat(),
            'sum'=>$sum,
            'group_id'=>$admin->group_id,
        ]);
    }


    /**
     * @menu 排队上线中的文章
     */
    public function article_queue(){
    	$rs = Article::article_queue();
    	return view('Admin.Article.article_queue')->with([
            'list' => $rs['list'],
            #'cats'=>Admin::all_list(),
        ]);
    }


    /**
     * @menu 排队上线中的视频
     */
    public function video_queue(){
    	$rs = Article::video_queue();
    	return view('Admin.Article.video_queue')->with([
            'list' => $rs['list'],
            #'cats'=>Admin::all_list(),
        ]);
    }

    /**
     * @menu 每日上线统计
     */
    public function day_online(){
        $list = DB::table('check_day_online');
        $this->_search($list, $search);
        $this->_order($list, ['id'=>'desc']);

        if(!isset($search['ymd'])){
            $list->where('ymd',date('Ymd'));
            $search['ymd'] = date('Ymd');
        }
        $sum = $list->sum('total');
        $list = $list->paginate(20);

        return view('Admin.Article.day_online')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::article_cat(),
            'video_cats'=>Article::video_cat(),
            'sum'=>$sum,
        ]);
    }

    /**
     * @menu 已拒绝文章
     * @return [type] [description]
     */
    public function refund_article(){
        $list = DB::connection('db2')->table('article')->select($this->field);
        $this->_search($list, $search);

        $list->where([
            ['status','=',2],
  
        ])->whereIn('type_of_article',[1,2]);

        $this->_order($list, ['id'=>'desc']);
        $list = Article::article_list($list);

        return view('Admin.Article.refund_article')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::article_cat(),
        ]);
    }

    /**
     * @menu 已拒绝视频
     * @return [type] [description]
     */
    public function refund_video(){
        $list = DB::connection('db2')->table('video')->select($this->field);
        $this->_search($list, $search);

        $list->where([
            ['status','=',2],
        ])->whereIn('type_of_article',[3]);

        $this->_order($list, ['id'=>'desc']);
        $list = Article::article_list($list);

        return view('Admin.Article.refund_video')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::video_cat(),
        ]);
    }

    /**
     * @menu 线上文章
     * @return [type] [description]
     */
    public function line_article(){
        $list = DB::table('article')->select($this->field);
        $this->_search($list, $search,[],[],'article',$words);

        $map = [
            ['status','=',0],
            ['downline','=',1],
            ['type_of_article','<',3]
        ];

        #$list->where($map)->whereIn('type',$this->admin['article_cats'])->whereIn('type_of_article',[1,2]);
        $list->where($map);

        $this->_order($list, ['id'=>'desc']);
        $list = Article::line_article_list($list,$words);
        return view('Admin.Article.line_article')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::article_cat(),
        ]);
    }

    /**
     * @menu 线上视频
     * @return [type] [description]
     */
    public function line_video(){
        $list = DB::table('article')->select($this->field);
        $this->_search($list, $search,[],[],'article',$words);

        $map = [
            ['status','=',0],
            ['downline','=',1],
            ['type_of_article','=',3]
        ];

        #$list->where($map)->whereIn('type',$this->admin['article_cats'])->whereIn('type_of_article',[3]);
        $list->where($map);

        $this->_order($list, ['id'=>'desc']);
        $list = Article::line_article_list($list,$words);
       return view('Admin.Article.line_video')->with([
            'list' => $list,
            '_search'=>$search,
            'cats'=>Article::video_cat(),
        ]);
    }

    /**
     * 下线
     * @return [type] [description]
     */
    public function ajax_downline($id){
        $data = DB::table('article')->where('id',$id)->first(['type','type_of_article']);
        if(empty($data)){
            die(json_encode(['status'=>0]));
        }

        if(DB::table('article')->where('id',$id)->update(['downline'=>0]) ){
            if($data->type_of_article==3){
                $key1 = config('rediskey.vod_params_one')[$data->type];
                $key1 = config('rediskey.vod_params_zero')[$data->type];
            }else{
                $key1 = config('rediskey.article_params_one')[$data->type];
                $key2 = config('rediskey.article_params_zero')[$data->type];
            }
            
            Redis::zrem($key1,$id);
            Redis::zrem($key2,$id);
            DB::table('user_collection_article')->where('aid',$id)->update(['status'=>0]);
            die(json_encode(['status'=>1,'data'=>$id]));
        }else{
            die(json_encode(['status'=>0]));
        }
    }

    public function ajax_delete_queue($id){
        $data = DB::table('check_article_queue')->where('id',$id)->first();
        $admin =DB::table('admindata')->where('id',$this->admin['id'])->first(['group_id']);
        if($admin->group_id==1){
            $delete = DB::table('check_log')->where([
                ['type','=',$data->type],
                ['article_id','=',$data->article_id],

            ])->delete();
            $bool = DB::table('check_article_queue')->where('id',$id)->delete();
        }else{
            $delete = DB::table('check_log')->where([
                ['type','=',$data->type],
                ['article_id','=',$data->article_id],
                ['admin_id','=',$this->admin['id']]
            ])->delete();
            $bool = DB::table('check_article_queue')->where('id',$id)->where('admin_id',$this->admin['id'])->delete();
        }
        $status = ($bool && $delete)?1:0;
        die(json_encode(['status'=>$status,'info'=>"statsu:$status",'data'=>$id]));
    }

    /**
     *  @menu 测试
     */
    public function test(){
        $dd = DB::connection('db2')->table('article_line')->first();
    
        $search = "你好的 中国";
        $sphinxmatch = sphinxClient::getClient()->Query($search, 'article');
        dd($sphinxmatch);
        if ($sphinxmatch['total'] > 0) {
            $ids = sphinxClient::getClient()->getids($sphinxmatch['matches']);
        }
    }


}  